package com.whkjdx.examtool.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.whkjdx.examtool.config.Const;
import com.whkjdx.examtool.entity.Option;
import com.whkjdx.examtool.entity.Question;
import com.whkjdx.examtool.feign.AnswerFeign;
import com.whkjdx.examtool.feign.dto.*;
import com.whkjdx.examtool.repository.QuestionRepository;
import com.whkjdx.examtool.web.request.ExamRequest;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xucong
 * @Date: 19:45 2022/1/31
 * @Description:
 * @Version v1.0
 */
@Slf4j
@Service
public class QuestionService {

    @Autowired
    AnswerFeign answerFeign;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    QuestionRepository questionRepository;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    public void createIndex(){
        elasticsearchRestTemplate.indexOps(Question.class).create();
    }

    public void deleteAll(){
        questionRepository.deleteAll();
    }

    public void quertQuestion(){

        for (Map.Entry<String, List<String>> stringListEntry : Const.CONFIG.entrySet()) {
            String cookie = stringListEntry.getKey();
            for (String s : stringListEntry.getValue()) {
                try {
                    queryPaperRecored(cookie,s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void queryPaperRecored(String cookie,String s){
        try {
            String data = answerFeign.queryAnswerPaperDetails(cookie, s);
            ExamResponse<Detail> examResponse = objectMapper.readValue(data,
                    new TypeReference<ExamResponse<Detail>>() {
                    });

            Detail detail = examResponse.getData();
            String title = detail.getTitle();

            for (PaperStructures paperStructure : detail.getPaperStructures()) {

                String answerMode = paperStructure.getAnswerMode();
                // 单选题
                if ("SingleSelection".equals(answerMode)){
                    handleData(title,paperStructure);
                }
                // 多选题
                if ("MultiSelection".equals(answerMode)){
                    handleMultiData(title,paperStructure);
                }
                // 判断题
                if ("Judgement".equals(answerMode)){
                    handleData(title,paperStructure);
                }
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public void handleData(String title,PaperStructures paperStructures){
        List<Question> questionList = paperStructures.getQuestions().stream().map(item -> {
            Question question = new Question();
            question.setId(item.getId());
            question.setTitle(title);
            question.setStem(item.getStem());
            question.setAnswer(item.getAnswer().getId());
            question.setAnswerMode(item.getAnswerMode());
            List<Option> optionList = item.getAnswerArea().getOptionList().stream().map(optionItem -> {
                Option option = new Option();
                option.setId(optionItem.getId());
                option.setContent(optionItem.getContent());
                option.setScore(optionItem.getScore());
                return option;
            }).collect(Collectors.toList());

            question.setOptionList(optionList);

            return question;
        }).collect(Collectors.toList());

        questionRepository.saveAll(questionList);
    }
    public void handleMultiData(String title,PaperStructures paperStructures){
        List<Question> questionList = paperStructures.getQuestions().stream().map(item -> {
            Question question = new Question();
            question.setId(item.getId());
            question.setTitle(title);
            question.setStem(item.getStem());

            String answer = "";
            for (int i = 0; i < item.getAnswer().getIdList().size(); i++) {
                String s = item.getAnswer().getIdList().get(i);
                if (i == item.getAnswer().getIdList().size()-1){
                    answer = answer + s;
                }else{
                    answer = answer + s +",";
                }
            }
            question.setAnswer(answer);
            question.setAnswerMode(item.getAnswerMode());
            List<Option> optionList = item.getAnswerArea().getOptionList().stream().map(optionItem -> {
                Option option = new Option();
                option.setId(optionItem.getId());
                option.setContent(optionItem.getContent());
                option.setScore(optionItem.getScore());
                return option;
            }).collect(Collectors.toList());

            question.setOptionList(optionList);

            return question;
        }).collect(Collectors.toList());

        questionRepository.saveAll(questionList);
    }

    public List<Question> search(String keyword){
        QueryBuilder query = QueryBuilders.matchQuery("stem", keyword);
        Iterable<Question> search = questionRepository.search(query);
        ArrayList<Question> questions = Lists.newArrayList(search);
        return questions;
    }

    public void exam(ExamRequest request){
        URI uri = URI.create(request.getUrl());
        Map<String,String> param = new HashMap<>();
        String query = uri.getQuery();
        String[] split = query.split("&");
        for (String s : split) {
            String[] split1 = s.split("=");
            param.put(split1[0],split1[1]);
        }


        String data = answerFeign.startAnswerPaper(request.getCookie(), param.get("arrangementId"), param.get("resourcePackageId"));
        log.info("page {}",data);

        try {
            ExamResponse<AnswerPaper> examResponse = objectMapper.readValue(data,
                    new TypeReference<ExamResponse<AnswerPaper>>() {
                    });

            AnswerPaper answerPaper = examResponse.getData();

            String arrangementId = answerPaper.getArrangementId();
            String studentTestActivityScoreId = answerPaper.getStudentTestActivityScoreId();
            String answerPaperRecordId = answerPaper.getAnswerPaperRecordId();
            String resourcePackageId = answerPaper.getResourcePackageId();
            Integer tempSaveAnswerExpire = answerPaper.getTempSaveAnswerExpire();

            SubmitPagerAnswer submitPagerAnswer = new SubmitPagerAnswer();
            submitPagerAnswer.setAnswerPaperRecordId(answerPaperRecordId);


            LinkedList<QuestionAnswerList> questionAnswerLists = new LinkedList<>();

            List<PsOutputDto> psOutputDto = answerPaper.getPaper().getPsOutputDto();
            for (int i = 1; i < psOutputDto.size(); i++) {
                PsOutputDto psOutputDto1 = psOutputDto.get(i);
                List<PaperQuestionList> paperQuestionList = psOutputDto1.getPaperQuestionList();
                for (PaperQuestionList questionList : paperQuestionList) {
                    String questionId = questionList.getQuestionId();

                    Optional<Question> byId = questionRepository.findById(questionId);

                    if (byId.isPresent()) {
                        Question question = byId.get();
                        String answer = question.getAnswer();
                        Map<String,Object> content = new HashMap<>(1);
                        if (answer.contains(",")){
                            String[] answerarry = answer.split(",");
                            content.put("idList",answerarry);
                        }else{
                            content.put("id",answer);
                            log.info("找到题目{},答案装填中",questionId);
                        }


                        QuestionAnswerList questionAnswerList = new QuestionAnswerList();
                        questionAnswerList.setQuestionId(questionId);
                        questionAnswerList.setContent(objectMapper.writeValueAsString(content));
                        questionAnswerLists.add(questionAnswerList);
                    }else{
                        log.info("没有找到该题{}",questionId);
                    }

                }
            }
            submitPagerAnswer.setQuestionAnswerList(questionAnswerLists);
            String answer = objectMapper.writeValueAsString(submitPagerAnswer);

            Map<String,Object> submitAnswerParam = new HashMap<>();
            submitAnswerParam.put("arrangementId",arrangementId);
            submitAnswerParam.put("studentTestActivityScoreId",studentTestActivityScoreId);
            submitAnswerParam.put("answerPaperRecordId",answerPaperRecordId);
            submitAnswerParam.put("tempSaveAnswerExpire",tempSaveAnswerExpire);
            submitAnswerParam.put("resourcePackageId",resourcePackageId);
            submitAnswerParam.put("temp","0");
            submitAnswerParam.put("paperAnswerResult",answer);
            String s = answerFeign.submitAnswerPaper(request.getCookie(),submitAnswerParam);
            log.info("提交考试答卷 {}",s);
            queryPaperRecored(request.getCookie(),answerPaperRecordId);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
